<template>
  <div class="lab-file" v-loading="requesting">
    <el-table :data="dataSource" :row-key="element.props.resourceId">
      <el-table-column type="index" label="序号" align="center"></el-table-column>
      <el-table-column label="文件名" align="center" prop="resourceName"></el-table-column>
      <el-table-column label="文件类型" align="center" prop="resourceSuffix"></el-table-column>
      <el-table-column label="资源分类" align="center" prop="resourceType"></el-table-column>
      <el-table-column label="更新日期" align="center" prop="updateAt"></el-table-column>
      <el-table-column label="操作" width="200px">
        <template slot="header" slot-scope="scope">
          <el-upload
              :action="uploadUrl"
              :headers="uploadHeader"
              :name="element.props.limit > 1 ? 'files' : 'file'"
              :data="uploadData"
              :limit="element.props.limit"
              :multiple="element.props.limit > 1"
              :file-list="dataSource"
              :show-file-list="false"
              :on-exceed="onExceed"
              :on-success="onSuccess"
              :auto-upload="true">
            <el-button v-if="scope && uploadAbled && dataSource.length < element.props.limit" slot="default" type="primary" circle icon="el-icon-upload2"></el-button>
          </el-upload>
        </template>
        <template slot-scope="scope">
          <el-button v-if="previewAbled" type="success" icon="el-icon-view" circle @click="onPreview(scope.row)" title="预览"></el-button>
          <el-button v-if="downloadAbled" type="warning" icon="el-icon-download" circle @click="onDownload(scope.row)" title="下载"></el-button>
          <el-button v-if="selfType !== 'view' && removeAbled" type="danger" icon="el-icon-delete" circle @click="onRemove(scope.row, scope.$index)" title="删除"></el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import LabBase from "../../mixins/LabBase";
import LabRequest from "../../mixins/LabRequest";
import Util from "../../utils/Util";

export default {
  name: "LabFile",
  mixins: [LabBase,LabRequest],
  data() {
    return {
      dataSource: [ ],
      uploadAbled: true,
      previewAbled: true,
      downloadAbled: true,
      removeAbled: true,
      flexProps: ['entityValue','entityType','resourceType']
    };
  },
  computed: {
    uploadUrl(){
      if (this.labDesign.switch) {
        return '#'
      } else {
        const { limit } = this.element.props
        if (limit < 2) {
          return this.$Util.mergeUrl(process.env.VUE_APP_BASE_API,'/resource/upload?appId=' + this.appInfo.appId)
        }
        return this.$Util.mergeUrl(process.env.VUE_APP_BASE_API,'/resource/uploads?appId='  + this.appInfo.appId)
      }
    },
    uploadHeader(){
      return { Authorization: 'Bearer ' + this.$AuthStorage.getAccessToken() }
    },
    uploadData(){
      const map = this.$Util.copy(this.modelData)
      this.flexProps.forEach(key => {
        Reflect.set(map, key, this.getLocalValue(key))
      })
      return map
    }
  },
  created() {
    this.$LabRender.autoFill(this.element, this)
    this.loadSource([])
  },
  methods: {
    onSuccess(response){
      this.$resultMsg(this, response, true)
      if (response.code === 200) {
        const { resourceId } = response.data
        if (resourceId) {
          const resourceIds = Util.toArray(this.modelData[this.element.mapper])
          resourceIds.push(resourceId)
          this.$set(this.modelData, this.element.mapper,resourceIds)
        }
        this.dispatchEvent('onSuccess', { response })
            .then(() => {
              this.loadSource([])
            })
      }
    },
    onRemove(file) {
      this.$remove(this, '/resource/delete/' + file.resourceId + '?appId=' + this.appInfo.appId)
      .then(res => {
        this.$resultMsg(this, res)
        if (res.code === 200) {
          this.dispatchEvent('onSuccess', { file })
              .then(() => {
                this.loadSource([])
              })
        }
      })
    },
    onPreview(file) {
      const url = this.$Util.mergeUrl(process.env.VUE_APP_BASE_API, '/resource/preview/' + file.resourceId)
      /*const perview = window.open(url + '?access_token=' + this.$AuthStorage.getAccessToken())
      perview.onload = function () {
        perview.document.title = file.resourceName
      }*/
      this.openNewWindow(url + '?access_token=' + this.$AuthStorage.getAccessToken() + '&appId=' + this.appInfo.appId, file.resourceName)
    },
    openNewWindow(url, title) {
      window.open(url, title)
      // const myWindow = window.open(url,title,'menubar=0,toolbar=0,width=1024,height=1024');
      // myWindow.document.write("<p>这是'我的窗口'</p>");
      // myWindow.focus();
      /*const win = window.open('about:blank','','menubar=0,toolbar=0,width=1024,height=1024');
      win.document.title = title;
      const iframe = document.createElement('iframe');
      iframe.src = url;
      iframe.style.width = '100%';
      iframe.style.height = '100vh';
      iframe.style.margin = '0';
      iframe.style.padding = '0';
      iframe.style.overflow = 'hidden';
      iframe.style.border = 'none';
      win.document.body.style.margin = '0';
      win.document.body.appendChild(iframe);*/
    },
    onDownload(file) {
      const url = this.$Util.mergeUrl(process.env.VUE_APP_BASE_API, '/resource/download/' + file.resourceId)
      window.open(url + '?access_token=' + this.$AuthStorage.getAccessToken() + '&appId=' + this.appInfo.appId)
    },
    onExceed(files, fileList) {
      this.$resultMsg(this, { msg: '超出最大数量'})
      console.info('超出数量',files, fileList)
    },
    getLocalValue(key){
      const confVal = Util.callPropValue(this.element.props,key)
      if (confVal) {
        const value = Util.callPropValue(this.modelData,confVal)
        return value || confVal
      }
      return ''
    },
    refreshValue(){
      const resourceIds = []
      this.dataSource.forEach(item => {
        resourceIds.push(item.resourceId)
      })
      this.$set(this.modelData, this.element.mapper,resourceIds)
    },
    loadSource(localFilters){
      this.dataSource.splice(0, this.dataSource.length)
      const resourceIds = Util.toArray(this.modelData[this.element.mapper])
      if (!Util.isEmpty(resourceIds)) {
        this.addFilter({ field:'resourceId', op: 'in',value: resourceIds })
      } else {
        this.flexProps.forEach(key => {
          const value = this.getLocalValue(key)
          this.addFilter({ field: key, op: '=',value: value })
        })
      }
      const sourceRequest = this.findRequest('source')
      if (!sourceRequest) {
        this.requesting = true
        this.pageInfo.filters = this.sourceFilters
        this.$post('/resource/queryPage?appId=' + this.appInfo.appId, this.pageInfo)
            .then(res => {
              if (res.code === 200 && !Util.isEmpty(res.data)) {
                this.dataSource = res.data.records
                this.refreshValue()
              }
              this.sourceFilters.splice(0, this.sourceFilters.length)
              setTimeout(() => {
                this.requesting = false
              }, 100)
            })
      } else {
        const bodyArgs = this.getBody(sourceRequest,this.modelData)
        if (!Util.isEmpty(localFilters)) {
          if (Util.isArray(localFilters)) {
            localFilters.forEach(item => this.addFilter(item))
          } else {
            this.addFilter(localFilters)
          }
        }
        this.dispatchRequest('source',this.modelData, bodyArgs)
            .then(res => {
              if (!Util.isEmpty(res)) {
                if (this.$Util.isArray(res)) {
                  this.dataSource = res
                } else {
                  this.dataSource.push(res)
                }
                this.refreshValue()
              } else {
                console.info('节点数据源请求:', this.element, res)
              }
              this.sourceFilters.splice(0, this.sourceFilters.length)
              setTimeout(() => {
                this.requesting = false
              }, 100)
            })
      }
    }
  }
}
</script>

<style lang="scss">
  .lab-file {
    display: flex;
    justify-content: flex-start;
    flex-flow: column;
  }
</style>
